package com.yhy.common.jxls;

import com.google.common.collect.Maps;
import com.yhy.common.dto.BaseMngDTO;
import com.yhy.common.exception.BusinessException;
import com.yhy.common.service.BaseMngService;
import com.yhy.common.utils.YhyUtils;
import com.yhy.common.vo.BusModuleSetting;
import org.apache.poi.util.IOUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-3-23 下午2:31 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */
public abstract class MyJxlsExportSupport<T extends BaseMngDTO> {

	protected Logger LOGGER = LoggerFactory.getLogger(getClass());
	public final static String DATA_KEY = "data";
	private MyJxlsExportConfig jxlsExportConfig;

	public MyJxlsExportSupport() {
	}

	public MyJxlsExportSupport(MyJxlsExportConfig jxlsExportConfig) {
		this.jxlsExportConfig = jxlsExportConfig;
	}

	public Map<String, Object> processDatas(T baseDTO) {
		Map<String, Object> dataMap = Maps.newHashMap();
		dataMap.put("baseDTO", baseDTO);
		dataMap.put("rtnList", getBaseService().queryPageData(baseDTO));
		return dataMap;
	}

	/**
	 * 导出数据
	 * @param datas
	 * @return
	 */
	public void exportData(Map<String, Object> datas, OutputStream os) {
		InputStream exportTemplate = null;
		try {
			exportTemplate = YhyUtils.getInputStream(getTemplatePath());
			Context context = new Context();
			context.putVar(DATA_KEY, datas);
			JxlsHelper.getInstance().processTemplate(exportTemplate, os, context);
			// OutputStream os = new FileOutputStream("target/object_collection_output.xls")
			// JxlsHelper.getInstance().processTemplate(exportTemplate, os, context);
		} catch (Exception e) {
			throw new BusinessException("导出错误", e);
		} finally {
			IOUtils.closeQuietly(exportTemplate);
		}
	}

	public String getTemplatePath() {
		return jxlsExportConfig.getTemplatePath();
	}

	public MyJxlsExportConfig getJxlsExportConfig() {
		return jxlsExportConfig;
	}

	public void setJxlsExportConfig(MyJxlsExportConfig jxlsExportConfig) {
		this.jxlsExportConfig = jxlsExportConfig;
	}

	protected abstract BaseMngService getBaseService();

}
